package cn.ljl.pet.service.impl;

import cn.ljl.basic.exception.BusinessException;
import cn.ljl.basic.service.IBaiduAiAuditService;
import cn.ljl.basic.util.*;
import cn.ljl.order.domain.OrderPetAcquisition;
import cn.ljl.order.mapper.OrderPetAcquisitionMapper;
import cn.ljl.org.domain.Employee;
import cn.ljl.org.domain.Shop;
import cn.ljl.org.mapper.EmployeeMapper;
import cn.ljl.org.mapper.ShopMapper;
import cn.ljl.pet.Dto.OrderDto;
import cn.ljl.pet.domain.SearchMasterMsg;
import cn.ljl.pet.domain.SearchMasterMsgAuditLog;
import cn.ljl.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.ljl.pet.mapper.SearchMasterMsgMapper;
import cn.ljl.pet.query.SearchMasterMsgQuery;
import cn.ljl.pet.service.ISearchMasterMsgService;
import cn.ljl.basic.service.impl.BaseServiceImpl;
import cn.ljl.user.domain.Logininfo;
import cn.ljl.user.domain.User;
import cn.ljl.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Override
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {
                //添加到数据库
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        msg.setUserId(user.getId());
        searchMasterMsgMapper.save(msg);//自增id
        //百度ai只能审核
        Boolean boo1 = baiduAiAuditService.textAudit(msg.getName() + msg.getTitle());
        Boolean boo2 = baiduAiAuditService.imageAudit(msg.getResources());
    if (boo1 && boo2) {//审核通过
        msg.setState(1);
        //添加审核日志
        SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
        log.setMsgId(msg.getId());
        log.setState(1);
        log.setNote("审核成功");
        searchMasterMsgAuditLogMapper.save(log);
        //获取李客户最近的店铺
        Point point = DistanceUtils.getPoint(msg.getAddress());
        Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
        if (nearestShop != null) {//找到了最劲的店铺
            msg.setShopId(nearestShop.getId());
            //发消息到店铺
            System.out.println("你有新的订单"+msg.getAddress()+"接回宠物");

        }else {//50公里内没有找到
            msg.setState(3);//放到寻主池 - 1.没有最近的店铺  2.拒单
            //发消息-用户
            //SmsUtils.sendSms("你附近暂时没有店铺,请耐心等待!!!");
            System.out.println("你附近暂时没有店铺,请耐心等待!!!");
             }
        searchMasterMsgMapper.update(msg);
        return new AjaxResult();
    }else {
        //审核不通过
        //添加审核日志
        SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
        log.setMsgId(msg.getId());
        log.setState(0);
        log.setNote("审核失败");
        searchMasterMsgAuditLogMapper.save(log);

        //发消息-用户
        //SmsUtils.sendSms("寻主消息发布失败,请重新发布!!!");
        System.out.println("寻主消息发布失败,请修改之后重新发布!!!");

        //删除寻主消息
        searchMasterMsgMapper.del(msg.getId());

        return AjaxResult.me().setSuccess(false).setMsg("寻主消息发布失败,请修改之后重新发布!!!");


    }


    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //用户查询自己的寻主消息 - 设置User_id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询已完成寻主消息
        query.setState(2);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if(employee.getShop_id()!=null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询寻主池寻主消息
        query.setState(3);
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询待处理寻主消息
        query.setState(1);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if(employee.getShop_id()!=null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(OrderDto orderDto) {

        //平台将寻主消息分给给你这个店铺
        //店铺接收了，指派一个人去接宠物
        //判断订单是否存在 - 说明有人已经去处理了 - 不应该重复接单
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgId(orderDto.getMsgId());
        if(order!=null && order.getState()==0){//有订单，并且当前订单是待处理 - 处理请求来了
            throw new BusinessException("订单正在处理，请勿重复接单!!!");
        }
        //1.生成收购订单
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(orderDto.getMsgId());
        OrderPetAcquisition newOrder = createOrder(msg,orderDto);
        orderPetAcquisitionMapper.save(newOrder);
        //2.告诉处理人在规定时间内去接回宠物：发短信 2day
        //Employee employee = employeeMapper.loadById(orderDto.getHandler());
        //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请在2天之内去"+msg.getAddress()+"接回宠物");
        System.out.println("你有新的订单，请在2天之内去"+msg.getAddress()+"接回宠物");
    }

    private OrderPetAcquisition createOrder(SearchMasterMsg msg, OrderDto orderDto) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()));
        order.setDigest(orderDto.getNote());
        //最后确认时间 - 2天之后的此刻
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        order.setPrice(msg.getPrice());
       // order.setPaytype(0);
        //order.setState(); - 正在处理，待处理0
        //order.setPetId(); - 没有，宠物接后来之后才会有
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(orderDto.getHandler());
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }
}
